package hnfnu.zmq;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author jammy
 * @since 2024/1/19 14:03
 */

public class MarkDown {

    private static final Logger log = LoggerFactory.getLogger(MarkDown.class);

    private static String fileName = "./test.md";
    private static Boolean append = false;
    private static File file;
    private static FileWriter mdWriter;

    static {
        file = new File(fileName);
        try {
            mdWriter = new FileWriter(file, append);
        } catch (IOException e) {
            log.warn("markdown init failed!");
        }
    }


    public MarkDown writeTitle(TitleLevel level, String msg) throws Exception {
        if (isStringValid(msg)) {
            throw new RuntimeException("内容包含特殊字符");
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(level.getLevel()).append(msg).append("\n");
        mdWriter.write(stringBuilder.toString());
        mdWriter.flush();
        return this;
    }

    public MarkDown writeContent(ContentType beginType, String begin, String after) throws Exception {
        if (isStringValid(begin) || isStringValid(after)) {
            throw new RuntimeException("内容包含特殊字符");
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(beginType.getType()).append(begin).append(beginType.getType())
                .append(after).append("\n");
        mdWriter.write(stringBuilder.toString());
        mdWriter.flush();
        return this;
    }

    public MarkDown writeLine() throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("***").append("\n");
        mdWriter.write(stringBuilder.toString());
        mdWriter.flush();
        return this;
    }

    public void closeAndExport(HttpServletResponse response) {
        try {
            mdWriter.close();
            FileUtils.copyFile(file, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("", e);
        } finally {
            file.delete();
        }
    }

    public void closeAndExport() {
        try {
            mdWriter.close();
        } catch (IOException e) {
            throw new RuntimeException("", e);
        }
    }

    private boolean isStringValid(String input) {
        return !input.matches(".*[\t\n\r].*");
    }
}
